package com.jh.paymentchannel.msdf.common;

import com.jh.paymentchannel.msdf.algorithm.Base64;
import com.jh.paymentchannel.msdf.algorithm.RSAHelper;
import org.apache.commons.codec.Charsets;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 
 * @author Luke
 *
 */
public class SignatureHelper {
	private static Log log = LogFactory.getLog(SignatureHelper.class);

	/**
	 * 针对机构公钥对明文数据、上送签名，进行验签比对
	 * @param plainBytes
	 * @param signatureBase64
	 * @return
	 * @throws Exception
	 */
    public static boolean verifyByBase64(byte[] plainBytes, String signatureBase64) throws Exception {
    	try {
        	// byte[] contentBytes = plainConent.getBytes(charset);
        	byte[] signatureBytes = Base64.decode(signatureBase64);
        	return RSAHelper.verify(plainBytes, CertServiceSingleton.getPubliceKey(), signatureBytes);
    	}
    	catch(Exception e) {
    		log.error(e, e);
    		throw new Exception("验证签名异常");
    	}
    }

	/**
	 * 针对机构公钥对明文数据进行加密，转Base64码
	 * @param content
	 * @return
	 * @throws Exception
	 */
    public static String encrypt2Base64(String content) throws Exception {
    	try {
	    	byte[] encrptyBytes = RSAHelper.encrypt(CertServiceSingleton.getPubliceKey(), content.getBytes(Charsets.UTF_8));
	    	return Base64.encode(encrptyBytes);
    	}
    	catch(Exception e) {
    		log.error(e, e);
    		throw new Exception("加密报文异常 ");
    	}
    }
    
    /**
     * 使用平台私钥对数据进行签名，转成Base64码
     * 
     * @param plainContent
     * @return
     * @throws Exception
     */
    public static String sign2Base64(String plainContent) throws Exception {
    	try {
	    	byte[] signature = RSAHelper.sign(CertServiceSingleton.getPrivateKey(), plainContent.getBytes(Charsets.UTF_8));
	        return Base64.encode(signature);
    	}
    	catch(Exception e) {
    		log.error(e, e);
    		throw new Exception("数据签名异常");
    	}
    }

    /**
     * 使用平台私钥解密被加密的数据
     * 
     * @param encryptedBase64
     * @return
     * @throws Exception
     */
    public static byte[] decrypt2Bytes(String encryptedBase64) throws Exception {
    	try {
	    	byte[] encrptyBytes = Base64.decode(encryptedBase64);
	    	return RSAHelper.decrypt2Bytes(CertServiceSingleton.getPrivateKey(), encrptyBytes);
    	}
    	catch(Exception e) {
    		log.error(e, e);
    		throw new Exception("业务报文无法解码 ");
    	}
    }
}
